package com.maozai.maozaimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maozai.common.constant.AuthServerConstant;
import com.maozai.common.utils.HttpUtils;
import com.maozai.common.utils.R;
import com.maozai.maozaimall.auth.feign.MemberFeignService;
import com.maozai.common.vo.MemberRespVo;
import com.maozai.maozaimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1 根据code换取access-tocke
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2375543451");
        map.put("client_secret", "9a3e9c3e7d32646728396227993304df");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        //System.out.println("code = " + code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com/", "/oauth2/access_token",
                "post", null, null, map);
        System.out.println("我要登陆了....");
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了 access_token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            String access_token = socialUser.getAccess_token();
            //知道是哪个社交用户
            //1 当前用户如果是第一次登录网站，自动注册进来(为当前社交用户生成会员信息账号);
            //登录或者注册这个社交用户
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            //System.out.println(oauthlogin);
            if (oauthlogin.getCode() == 0) {
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });

                log.info("登录成功，用户信息{}", data.toString());
                //TODO 1 默认发的令牌。session=sdlflsj。作用域：当前域；(解决子域session共享问题)
                //TODO 2 使用JSON得序列化方式来序列化对象数据到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                //session.setAttribute("wangdong", "jiajiale");
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
